package com.shu.qq.config.security.jwt;

import com.alibaba.fastjson.JSON;
import com.shu.qq.data.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Data
@Component
public class JwtTokenUtil {

    @Value("${token.secret}")
    private String secret;

    @Value("${token.expireTime}")
    private Long expiration;

    @Value("${token.header}")
    private String header;

    /**
     * 生成用户的token
     * @param user
     * @return
     */
    public String createUserToken(User user){
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder()
                .setAudience(user.getUsername()) //设置账号
                .setSubject(user.getRoles()) //设置权限
                .setExpiration(expirationDate) //设置过期时间
                .signWith(SignatureAlgorithm.HS512,secret)
                .compact();

    }

    /**
     * 生成一般的token
     * @param claims
     * @return
     */
    private String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder().setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 验证令牌
     *
     * @param claims       令牌
     * @param userDetails 用户
     * @return 是否有效
     */
    public Boolean validateToken(Claims claims, UserDetails userDetails) {
        String username = getAccountFromToken(claims);
        return (username.equals(userDetails.getUsername()) && !isTokenExpired(claims));
    }

    /**
     * 检查token是否过期
     * @param claims
     * @return
     */
    public Boolean isTokenExpired(Claims claims){
        try {
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return false;
        }
    }
    /**
     * 刷新令牌
     *
     * @param token 原令牌
     * @return 新令牌
     */
    public String refreshToken(String token) {
        String refreshedToken;
        try {
            Claims claims = getClaimsFromToken(token); //把之前的数据取出来重新封装一次。
            refreshedToken = generateToken(claims);
        } catch (Exception e) {
            refreshedToken = null;
        }
        return refreshedToken;
    }


    /**
     * 从token中获取claims
     * @param token
     * @return
     */
    public Claims getClaimsFromToken(String token){
        Claims claims;
        try {                                           //解析Claims部分加密的token
            claims = Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        }catch (Exception e){
            claims = null;
        }
        return  claims;
    }

    /**
     * 从Token获取Y用户的账号
     * @param claims
     * @return
     */
    public String getAccountFromToken(Claims claims){
        String account;
        try{
            account = claims.getAudience();
        }catch (Exception e){
            account = null;
        }
        return account;

    }

    public List<GrantedAuthority> getRolesFromToken(Claims claims){
        List<GrantedAuthority> roles;
        try{
            roles = strArrayToAuthorityList(claims.getSubject());
        }catch (Exception e){
            roles = null;
        }
        return roles;

    }
    public List<GrantedAuthority> strArrayToAuthorityList(String roles){
        List<String> rolesStr = JSON.parseArray(roles, String.class);
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        for (String role : rolesStr) {
            grantedAuthorities.add(new SimpleGrantedAuthority(role));
        }
        return grantedAuthorities;
    }
}
